package com.atguigu.study.controller;

import com.atguigu.study.service.ChatAssistant;
import dev.langchain4j.model.chat.StreamingChatModel;
import dev.langchain4j.model.chat.response.ChatResponse;
import dev.langchain4j.model.chat.response.StreamingChatResponseHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.function.Consumer;

/**
 * @author Marco
 * @Description
 * @date 2025/8/19 23:06
 * @email 3293336923@qq.com
 */
@RestController
public class StreamingChatModelController {

    @Autowired
    private StreamingChatModel streamingChatModel;
    @Autowired
    private ChatAssistant chatAssistant;


    @GetMapping("/chatstream/chat1")
    public Flux<String> chat1(@RequestParam(name = "prompt") String prompt) {

        return Flux.create(emitter -> {
            streamingChatModel.chat(prompt, new StreamingChatResponseHandler() {

//                按照一部分一部分的 返回给前端
                @Override
                public void onPartialResponse(String partialResponse) {
                    emitter.next(partialResponse);
                }

                @Override
                public void onCompleteResponse(ChatResponse chatResponse) {

                }

                @Override
                public void onError(Throwable throwable) {
                    throwable.printStackTrace();
                }
            });
        });

    }


//    只在 后台  进行 一点一点的 显示
    @GetMapping("/chatstream/chat2")
    public void chat2(String prompt) {
        streamingChatModel.chat(prompt, new StreamingChatResponseHandler() {
            @Override
            public void onPartialResponse(String partialResponse) {
                System.out.println(partialResponse);
            }

            @Override
            public void onCompleteResponse(ChatResponse chatResponse) {
                System.out.println("----response  over:" + chatResponse);
            }

            @Override
            public void onError(Throwable throwable) {
                throwable.printStackTrace();
            }
        });
    }


    @GetMapping("/chatstream/chat3")
    public Flux<String> chat3(@RequestParam(value = "prompt", defaultValue = "南京有什么好玩的？") String prompt) {

        return chatAssistant.chatFlux(prompt);

    }
}
